/**
 * Created by yanghaijin on 2018/5/16.
 */
/**
 * 房间ID生成器
 * */
let RoomIdGenerator = {
    _availableRoomIdArr: [],
    _sRoomId: 100000,
    _tRoomId: 999999,
    _sTmpRoomId: 100000,
    _tTmpRoomId: 999999,
    _index: -1,
    /**
     * 生成可用的RoomID数组
     * @return {void}
     * */
    generateRoomIdArr: function () {
        let start_time = new Date();
        for (let i = 1; i <= 9; i++) {
            for (let j = 0; j <= 9; j++) {
                for (let a = 0; a <= 9; a++) {
                    for (let b = 0; b <= 9; b++) {
                        for (let c = 0; c <= 9; c++) {
                            for (let d = 0; d <= 9; d++) {
                                let roomId = i * 100000 + j * 10000 + a * 1000 + b * 100 + c * 10 + d;
                                if (roomId >= this._sRoomId && roomId < this._tRoomId) {
                                    this._availableRoomIdArr.push(roomId);
                                }
                            }
                        }
                    }
                }
            }
        }

        function randomSort (a, b) {
            return Math.random() > 0.5 ? -1 : 1; // 用Math.random()函数生成0~1之间的随机数与0.5比较，返回-1或1
        }

        this._availableRoomIdArr.sort(randomSort);
        let elapsed = new Date() - start_time;
        elapsed /= 1000;
        console.log("生成可用的房间ID数组耗时【" + elapsed.toFixed(2) + "s】");
    },

    /**
     * 获得一个RoomID
     * @public
     * @return {Number}
     * */
    getRoomId: function () {
        if (this._availableRoomIdArr.length === 0) {
            this.generateRoomIdArr();
        }
        if (this._sTmpRoomId !== this._sRoomId || this._tTmpRoomId !== this._tRoomId) {
            console.log("Regenerate roomId _sTmpRoomId:", this._sTmpRoomId, " _tTmpRoomId:", this._tTmpRoomId);
            this._sRoomId = this._sTmpRoomId;
            this._tRoomId = this._tTmpRoomId;
            this.generateRoomIdArr();
        }
        return this._availableRoomIdArr.shift(); // 把数组的第一个元素从其中删除，并返回第一个元素的值。

        // this._index = Math.abs((this._index + 1) % this._availableRoomIdArr.length);
        // return this._availableRoomIdArr[this._index];
    },

    /**
     * 设置临时的RoomID
     * @param {Number} sTmpRoomId
     * @param {Number} tTmpRoomId
     * */
    setTmpRoomId: function (sTmpRoomId, tTmpRoomId) {
        this._sTmpRoomId = sTmpRoomId;
        this._tTmpRoomId = tTmpRoomId;
    }
};
module.exports = RoomIdGenerator;